package com.whsxt.listener;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.rabbitmq.client.Channel;
import com.whsxt.config.SmsProperties;
import com.whsxt.constant.QueueConstant;
import com.whsxt.model.AliSmsModel;
import com.whsxt.service.SmsLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author: caoqingwen
 * @CreateTime: 2021-03-22 18:02
 * @Description:
 */
@Component
@Slf4j
public class SmsListener {


    @Autowired
    private IAcsClient iAcsClient;

    @Autowired
    private SmsProperties smsProperties;

    @Autowired
    private SmsLogService smsLogService;


    /**
     * 处理发消息的监听
     *
     * @param message
     * @param channel
     */
    @RabbitListener(queues = {QueueConstant.PHONE_SEND_QUEUE}, concurrency = "3-5")
    public void smsHandler(Message message, Channel channel) {
        //拿到消息
        String msg = new String(message.getBody());
        String msg1 = message.getBody().toString();
        log.info(msg);
        log.info(msg1);
        AliSmsModel aliSmsModel = JSON.parseObject(msg, AliSmsModel.class);
        //发短信了
        try {
            realSendMsg(aliSmsModel);
            log.info("短息发送成功");
            //记录数据库
            smsLogService.saveMsg(aliSmsModel);
            //签收消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);

        } catch (Exception e) {
            log.error("发送短息失败");

        }

    }


    /**
     * 发送短息
     *
     * @param aliSmsModel
     */
    private void realSendMsg(AliSmsModel aliSmsModel) throws ClientException {
        CommonRequest commonRequest = new CommonRequest();
        //基本参数
        commonRequest.setVersion(smsProperties.getVersion());
        commonRequest.setMethod(MethodType.POST);
        commonRequest.setAction("SendSms");
        commonRequest.setRegionId(smsProperties.getRegionId());
        commonRequest.setDomain(smsProperties.getSysDomain());
        //给哪个手机号发
        commonRequest.putQueryParameter("PhoneNumbers", aliSmsModel.getPhoneNumbers());
        commonRequest.putQueryParameter("SignName", aliSmsModel.getSignName());
        commonRequest.putQueryParameter("TemplateCode", aliSmsModel.getTemplateCode());
        commonRequest.putQueryParameter("TemplateParam", aliSmsModel.getTemplateParam());

        //发送短信
        CommonResponse commonResponse = iAcsClient.getCommonResponse(commonRequest);
        System.out.println(commonResponse.getData());
        System.out.println(commonResponse.getHttpStatus());

    }


}
